

import WebSocket =require("ws")
import {messageType} from "./type"
const ws = new WebSocket.Server({ port: 8080 }, () => { // 监听接口
  console.log(`socket start, port:${8080}`)
})
// 总人数
let all = []
// 离开人数
let end = []
// 消息ID:
let messageIndex = 0;
const getUserNumber=()=>{
  let a=all.length+end.length;
  console.log("当前在线人数" + (all.length) + "-------一总访问人数" + a,'离开人数：'+end.length)
}
ws.on('connection', (client) => {
  client.on('message', (msg) => {
    console.log("来客户端的数据", msg);
    if(typeof msg=="string"){
      const user=JSON.parse(msg);
      if(!all.find((item)=>item.id==user.id)){
        all.push(user);
        client.send(createMessage(messageType.chat,`你好${user.name}`)); // 通过send方法来给前端发送消息
        broadcast(createMessage(messageType.user,`${user.name}加入房间`))
      }else{
        console.log("用户已经存在")
      }
    }
  })
  
  client.on('close', (msg) => {
    console.log("有人退出了",end.length)
    const user=all.pop();
    console.log(msg);
    end.push(user);
    // getUserNumber();
    // broadcast(createMessage(messageType.user,`${all.pop().name}退出房间`))
  })
})

/**
 * 广播
 * @param msg 
 */
const broadcast=(msg:string) => {
  ws.clients.forEach(function (client) {
    client.send(msg);
  });
}
const createMessage=(type:messageType, data)=> {
  messageIndex ++;
  if(type === messageType.user){
    return JSON.stringify({
      id: messageIndex,
      type: type,
      data: data,
      user:all
    });
  }
  return JSON.stringify({
      id: messageIndex,
      type: type,
      data: data
  });
}